package com.yx.fx.sys.web.aop;

import cn.hutool.core.util.ObjectUtil;
import com.yx.fx.common.model.response.Outcome;
import com.yx.fx.sys.web.aspect.InsertCheck;
import com.yx.fx.sys.web.business.SysUserBusiness;
import com.yx.fx.sys.web.model.UserInfo;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;


import javax.annotation.Resource;
import java.lang.reflect.Method;

import static com.yx.fx.common.constant.BaseConstant.ADMIN;

/**
 * @author 杨智杰
 * @date 2021/8/13 14:00
 **/
@Aspect
@Component
public class CheckAspect {

    @Resource
    private SysUserBusiness sysUserBusiness;

    @Pointcut("@annotation(com.yx.fx.sys.web.aspect.InsertCheck)")
    public void exudeService() {
    }

    @Around("exudeService()")
    public Outcome doAround(ProceedingJoinPoint pjp) {
        MethodSignature ms = (MethodSignature) pjp.getSignature();
        Method method = ms.getMethod();
        InsertCheck insertCheck = method.getAnnotation(InsertCheck.class);
        UserInfo loginUser = sysUserBusiness.getUserInfo();
        if (ObjectUtil.isNull(loginUser)) {
            return Outcome.failure("权限校验失败!请重新登录!").setCode(401);
        }
        if (loginUser.getAuthStrList().stream().anyMatch(i -> insertCheck.value().equals(i) || ADMIN.equals(i))) {
            try {
                return (Outcome) pjp.proceed();
            } catch (Throwable throwable) {
                throw new RuntimeException(throwable);
            }
        }
        return Outcome.failure("权限不足!").setCode(403);
    }

}
